//#include <string.h>
//#include <stdio.h>

//#include "hmac_sha1.h"
//#include "../sysdef.h"

#include "../os_common.h"

#define A_SHA_DIGEST_LEN	20

/*
 * F(P, S, c, i) = U1 xor U2 xor ... Uc
 * U1 = PRF(P, S || Int(i))
 * U2 = PRF(P, U1)
 * Uc = PRF(P, Uc-1)
 */

static VOID F(UCHAR *password,
              UCHAR *ssid,
              UINT ssidlength,
              UINT iterations,
              UINT count,
              UCHAR *output)
{
    UCHAR digest[36], digest1[A_SHA_DIGEST_LEN];
    UINT i, j;

    /* U1 = PRF(P, S || int(i)) */
    OS_MEMORY_COPY(digest,ssid,ssidlength);
    digest[ssidlength] = (UCHAR) ((count >> 24) & 0xff);
    digest[ssidlength + 1] = (UCHAR) ((count >> 16) & 0xff);
    digest[ssidlength + 2] = (UCHAR) ((count >> 8) & 0xff);
    digest[ssidlength + 3] = (UCHAR) (count & 0xff);
    
    hmac_sha1(digest,
              ssidlength + 4,
              (UCHAR *) password,
              (UINT) strlen(password),
              // digest,
              digest1);

    /* output = U1 */
    OS_MEMORY_COPY(output,digest1,A_SHA_DIGEST_LEN);

    for (i = 1; i < iterations; i++)
    {
        /* Un = PRF(P, Un-1) */
        hmac_sha1(digest1,
                  A_SHA_DIGEST_LEN,
                  (UCHAR *) password,
                  (UINT) strlen(password),
                  digest);
        OS_MEMORY_COPY(digest1,digest,A_SHA_DIGEST_LEN);

        /* output = output xor Un */
        for (j = 0; j < A_SHA_DIGEST_LEN; j++)
        {
            output[j] ^= digest[j];
        }
    }
}

/*
 * password - ascii string up to 63 characters in length
 * ssid - octet string up to 32 octets
 * ssidlength - length of ssid in octets
 * output must be 40 octets in length and outputs 256 bits of key
 */
UINT PasswordHash(UCHAR *password,
                 UCHAR  *ssid,
                 UINT	ssidlength,
                 UCHAR	*output)
{
    if ((strlen(password) > 63) || (ssidlength > 32))
        return 0;

    F(password,ssid,ssidlength,4096,1,output);
    F(password,ssid,ssidlength,4096,2,&output[A_SHA_DIGEST_LEN]);
    return 1;
}

VOID hexout(UCHAR *data, UINT datalen) 
{
//	printf("0x");
	//while (datalen-- > 0)
		//printf("%02x",(unsigned char)*data++);
	//printf("\n");
}


